import React, { useState, useContext, useEffect } from "react";
import { AppState } from "../App";
import { HeartIcon, DocumentTextIcon } from "@heroicons/react/solid";
import { FaLink, FaHandHoldingUsd } from "react-icons/fa";
import { ethers } from "ethers";
import axios from "axios";
import "../css/managerStyles.css";
import "../css/hualun.css";
import "../css/loader.css";


const Manager = () => {
  const App = useContext(AppState);
  const [Address, setAddress] = useState("");
  const [target, setTarget] = useState("");
  const [Description, setDescription] = useState("");
  const [PhotoHash, setPhotoHash] = useState("");
  const [selectedImage, setSelectedImage] = useState(null);
  const [selectedImageName, setSelectedImageName] = useState(null);
  const [showDeleteButton, setShowDeleteButton] = useState(false);
  const [showImage, setShowImage] = useState(false);
  const [loading, setLoading] = useState(false); 
  const [tittle, setTittle] = useState(""); 
  console.log(tittle);
  

  const handleImageChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (readerEvent) => {
        setSelectedImage(readerEvent.target.result);
        setSelectedImageName(file.name);
        setShowImage(false);
        uploadImageToPinata(file); 
      };
      reader.readAsDataURL(file);
    }
  };

  const uploadImageToPinata = async (file) => {
    setLoading(true); 
    console.log(file);
    const formData = new FormData();
    formData.append("file", file);
    console.log(formData);
    try {
      const response = await axios.post(
        "https://api.pinata.cloud/pinning/pinFileToIPFS",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization:
              "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJjYjgzNmJjOS0xMjgzLTQwMWEtOWU4MS0wY2I5Y2ZkMjk1N2UiLCJlbWFpbCI6Imd1MDIwNDEyQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaW5fcG9saWN5Ijp7InJlZ2lvbnMiOlt7ImlkIjoiRlJBMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfSx7ImlkIjoiTllDMSIsImRlc2lyZWRSZXBsaWNhdGlvbkNvdW50IjoxfV0sInZlcnNpb24iOjF9LCJtZmFfZW5hYmxlZCI6ZmFsc2UsInN0YXR1cyI6IkFDVElWRSJ9LCJhdXRoZW50aWNhdGlvblR5cGUiOiJzY29wZWRLZXkiLCJzY29wZWRLZXlLZXkiOiJiZTNjOGVkY2IxZTA0MThkODlkMSIsInNjb3BlZEtleVNlY3JldCI6Ijc1OTVhY2JlY2E0MjU0YmM1ZGNlZTc3YTg2MTQwNGJkNGNjMmI0ZDM3ZGYwOTIwOTY0YjgxMzYzNjhhOGNiOGIiLCJpYXQiOjE3MTMxNTE2Nzh9.MgxXFGogmDXnIf6Z0U_qJlAuLcDxW3NFWwNr7u_u8Wc", // 替换为您的Pinata API密钥
          },
        }
      );
      console.log(response.data.IpfsHash);
      setPhotoHash(response.data.IpfsHash); 
    } catch (error) {
      console.error("Error uploading image to Pinata:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleMouseEnter = () => {
    setShowDeleteButton(true);
  };

  const handleMouseLeave = () => {
    setShowDeleteButton(false);
  };

  const handleDeleteImage = () => {
    setSelectedImage(null);
    setSelectedImageName(null);
    setPhotoHash(""); 
    const fileInput = document.getElementById("fileInput");
    if (fileInput) {
      fileInput.value = "";
    }
  };

  const handleImageClick = () => {
    setShowImage(!showImage);
  };

  const Create = async () => {
    setLoading(true);
    try {
      console.log(PhotoHash);
      if (!loading) {
        const tx = await App.Foundationcontract.createAdminRequest(
          tittle,
          Description,
          Address,
          ethers.utils.parseUnits(target, 0), 
          PhotoHash
        );
        await tx.wait();
        alert("创建成功!");
        setTittle("");
        setAddress("");
        setTarget("");
        setDescription("");
        setPhotoHash("");
        window.location.reload();
      }
    } catch (error) {
      if (
        error.message ===
        "MetaMask Tx Signature: User denied transaction signature."
      ) {
        alert("用户拒绝了交易签名。");
      } else if (
        error.message ===
        "execution reverted: Only manager can calll this function"
      ) {
        alert("只有管理员可以调用此函数");
      } else {
        console.log(error.message);
        alert("只有管理员可以调用此函数");
      }
    }finally {
      setLoading(false); 
    }
  };

  return (
    <>
      <div className="divFFF">
      {loading && <div className="loading-circle"></div>}
        <section>
          <div className="containerDiv">
            <div className="divThree">
              <p>这里是此慈善合约的管理员可以创建请求。</p>
            </div>
            <div className="divFour">
              <h1>爱心筹款</h1>
              <div className="divFO">
                <div className="divP1">
                  <div className="relative">
                    <HeartIcon className="input-icon" />
                    <input
                      placeholder="收款人地址"
                      value={Address}
                      onChange={(e) => setAddress(e.target.value)}
                      type="text"
                    />
                  </div>
                </div>
                <div className="divP1">
                  <div className="relative">
                    <FaHandHoldingUsd className="input-icon" />
                    <input
                      placeholder="目标金额"
                      value={target}
                      onChange={(e) => setTarget(e.target.value)}
                      type="email"
                    />
                  </div>
                </div>
                <div className="divP1">
                  <div class="relative">
                    <FaLink className="input-icon" />
                    <select
                      value={tittle}
                      onChange={(e) => setTittle(e.target.value)}
                      className="category-select"
                    >
                      <option value="">选择慈善类别</option>
                      <option value="教育资助">教育资助</option>
                      <option value="慈善救助">慈善救助</option>
                      <option value="环境保护">环境保护</option>
                      <option value="社会福利">社会福利</option>
                      <option value="文化艺术">文化艺术</option>
                    </select>
                  </div>
                </div>
                <div className="divP1">
                  <div class="relative">
                    <DocumentTextIcon className="input-icon" />
                    <input
                      placeholder="描述"
                      value={Description}
                      onChange={(e) => setDescription(e.target.value)}
                      id="message"
                      type="text"
                    ></input>
                  </div>
                </div>
                <div className="divP1">
                  <div class="relative">
                    <FaLink className="input-icon" />
                    <input
                      type="file"
                      id="fileInput"
                      accept="image/*"
                      className="imgInput"
                      onChange={handleImageChange}
                    />

                    {selectedImage && (
                      <>
                        <p onClick={handleImageClick}>
                          当前选择的图片: {selectedImageName}
                        </p>{" "}
                        <div
                          className="image-preview"
                          onMouseEnter={handleMouseEnter}
                          onMouseLeave={handleMouseLeave}
                        >
                          {showImage && (
                            <div className="image-preview">
                              <img src={selectedImage} alt="Preview" />
                              <button
                                onClick={handleDeleteImage}
                                className="delete-button"
                              >
                                删除
                              </button>
                            </div>
                          )}
                        </div>
                      </>
                    )}
                  </div>
                </div>
               
                <div className="p-2 w-full">
                  <button
                    onClick={Create}
                    className="flex mx-auto text-white bg-yellow-500 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded text-lg"
                  >
                    提交
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </>
  );
};

export default Manager;
